$(function() {
	var car_num = 100;
	var stringEl = $('.str3').liMarquee();
	var page=1;
	var origin = {
		car: [],
		order: []
	};
	var id, orderid, ordercont;
	var map = new AMap.Map('map', {
		resizeEnable: true,
		zoom: 11,
		center: [118.57, 24.82]
	});

	//构造路线导航类
	var driving = new AMap.Driving({
		map: map,
		//		panel: "panel"
	});
	$('.str3').on('click', function() {
		choosecar("{:url('/admin/anomaly/index',['op'=>'search'])}", '异常');
	})
	$('.page').html(page)
	AMapUI.loadUI(['overlay/SimpleMarker', 'overlay/SimpleInfoWindow', 'misc/PathSimplifier'], function(SimpleMarker, SimpleInfoWindow, PathSimplifier) {
		//节点颜色
		
		//轨迹
		var pathSimplifierIns = new PathSimplifier({
			zIndex: 100,
			map: map, //所属的地图实例
			getPath: function(pathData, pathIndex) {
				//返回轨迹数据中的节点坐标信息，[AMap.LngLat, AMap.LngLat...] 或者 [[lng|number,lat|number],...]
				return pathData.path;
			},
			getHoverTitle: function(pathData, pathIndex, pointIndex) {
				//返回鼠标悬停时显示的信息
				if(pointIndex >= 0) {
					//鼠标悬停在某个轨迹节点上
					return pathData.name + '，点:' + pointIndex + '/' + pathData.path.length;
				}
				//鼠标悬停在节点之间的连线上
				return pathData.name + '，点数量' + pathData.path.length;
			},
			renderOptions: {
				//轨迹线的样式
				pathLineStyle: {
					strokeStyle: 'red',
					lineWidth: 6,
					dirArrowStyle: true
				}
			}
		});
		//信息窗口
		var infoWindow;

		{if $Think.get.number}
		ajaxcar(origin, id, map, SimpleMarker, SimpleInfoWindow,pathSimplifierIns, PathSimplifier,encodeURI('{$Think.get.number}'),PathSimplifier,page);
		{else/}
		ajaxcar(origin, id, map, SimpleMarker, SimpleInfoWindow,pathSimplifierIns, PathSimplifier,PathSimplifier,page);
		{/if}
		
		
		
		$('.backcar').on('click', function() {
			$('.carlist ul').html("")
			$('.orderlist ul').html("")
			map.setZoomAndCenter(11, [118.57, 24.82]);
			pathSimplifierIns.hide();
			map.clearMap();
			{if $Think.get.number}
			ajaxcar(origin, id, map, SimpleMarker, SimpleInfoWindow,pathSimplifierIns, PathSimplifier,encodeURI('{$Think.get.number}'),PathSimplifier,page);
			{else/}
			ajaxcar(origin, id, map, SimpleMarker, SimpleInfoWindow,pathSimplifierIns, PathSimplifier,PathSimplifier,page);
			{/if}
		})
		$('.car_num').on('change', function() {
			$('.carlist ul').html("")
			$('.orderlist ul').html("")
			map.setZoomAndCenter(11, [118.57, 24.82]);
			pathSimplifierIns.hide();
			map.clearMap();
			car_num = $(this).val();
			{if $Think.get.number}
			ajaxcar(origin, id, map, SimpleMarker, SimpleInfoWindow,pathSimplifierIns, PathSimplifier,encodeURI('{$Think.get.number}'),PathSimplifier,page);
			{else/}
			ajaxcar(origin, id, map, SimpleMarker, SimpleInfoWindow,pathSimplifierIns, PathSimplifier,PathSimplifier,page);
			{/if}
		})
	})

	//请求数据car
	function ajaxcar(origin, id, map, SimpleMarker, SimpleInfoWindow,pathSimplifierIns, infoWindow{if $Think.get.number},number{/if},PathSimplifier,page) {
		var carload = layer.load(0, {
			shade:  [0.3,'#fff']
		});
		$('.carlist').css('display', 'block');
		$('.orderlist').css('display', 'none');
		$.ajax({
			type: "post",
			url: "{:url('cars')}",
			data: {
				pagesize: car_num
				{if $Think.get.number},number:number{/if}
			},
			success: function(res) {
				
				layer.close(carload);
				if(res.code == 1) {
					setTimeout(function() {
						$('.carlist ul').html("")
						$('.orderlist ul').html("")
						pathSimplifierIns.hide();
						map.clearMap();
						{if $Think.get.number}
						ajaxcar(origin, id, map, SimpleMarker, SimpleInfoWindow,pathSimplifierIns, PathSimplifier,encodeURI('{$Think.get.number}'),PathSimplifier,page);
						{else/}
						ajaxcar(origin, id, map, SimpleMarker, SimpleInfoWindow,pathSimplifierIns, PathSimplifier,PathSimplifier,page);
						{/if}
			
					}, 60000)
				if(typeof res == 'string') {
					origin.car = JSON.parse(res).data;
				} else {
					origin.car = res.data;
				};
				console.log(origin)
				//				}
				for(var caridx = 0; caridx < origin.car.length; caridx++) {
					carlistshow(caridx, origin);
					ulheight();
					if(origin.car[caridx].loc[0]){
					addcarMarker(origin, caridx, SimpleMarker);
					
					origin.car[caridx].point.on('click', function() {
						var carthat = this;
						clear(origin, this, map);
						console.log(1)
						openmessage(map, this, SimpleInfoWindow, infoWindow, 1);
						//循环遍历获取车辆id
						for(var index in carthat) {
							for(var index1 in carthat[index]) {
								if(index1 == "cont") {
									id = carthat[index].cont.carid;
									loc=carthat[index].cont.loc
									number=carthat[index].cont.number
								};
							};
						};
						map.setZoomAndCenter(11, loc);
						ordertitle(number)
						ajaxorder(origin, id, this, map, SimpleMarker, SimpleInfoWindow, pathSimplifierIns, infoWindow,PathSimplifier,page);
						$('.previous').on('click',function(){
							pathSimplifierIns.hide();
							$('.orderlist ul').html('');
							if(page<=1){
							}else{
								clearorder(origin, map) 
								page-=1
								$('.page').html(page)
							}
							ajaxorder(origin, id, carthat, map, SimpleMarker, SimpleInfoWindow, pathSimplifierIns, infoWindow,PathSimplifier,page);
						});
						$('.next').on('click',function(){
							pathSimplifierIns.hide();
							$('.orderlist ul').html('');
							clearorder(origin, map) 
							page+=1
							$('.page').html(page)
							ajaxorder(origin, id, carthat, map, SimpleMarker, SimpleInfoWindow, pathSimplifierIns, infoWindow,PathSimplifier,page);
						});
					})
					}
				};
				$('.carlist ul li').on('click', function() {
					var carlistidx = $(this).index();
					if(origin.car[carlistidx].point){
					var nod = origin.car[carlistidx].point;
					clear(origin, nod, map, id);
					openmessage(map, nod, SimpleInfoWindow, infoWindow, 1);
					for(var index in nod) {
						for(var index1 in nod[index]) {
							if(index1 == "cont") {
								id = nod[index].cont.carid;
							};
						};
					};
					map.setZoomAndCenter(11, origin.car[carlistidx].loc);
					ordertitle(origin.car[carlistidx].number)
					ajaxorder(origin, id, nod, map, SimpleMarker, SimpleInfoWindow, pathSimplifierIns, infoWindow,PathSimplifier,page);
					$('.previous').on('click',function(){
						pathSimplifierIns.hide();
						$('.orderlist ul').html('');
						clear(origin, nod, map, id);
						if(page<=1){
						}else{
							clearorder(origin, map) 
							page-=1
							$('.page').html(page)
						}
						ajaxorder(origin, id, nod, map, SimpleMarker, SimpleInfoWindow, pathSimplifierIns, infoWindow,PathSimplifier,page);
					});
					$('.next').on('click',function(){
						pathSimplifierIns.hide();
						$('.orderlist ul').html('');
						clearorder(origin, map) 
						page+=1
						$('.page').html(page)
						ajaxorder(origin, id, nod, map, SimpleMarker, SimpleInfoWindow, pathSimplifierIns, infoWindow,PathSimplifier,page);
					});
					}else{
						Err('暂无信息')
					}
				})
				
				}
			},
			error:function(){
				layer.close(carload);
				Err('请求失败')
			}
		})
	}
	//请求数据order
	function ajaxorder(origin, id, car, map, SimpleMarker, SimpleInfoWindow, pathSimplifierIns, infoWindow,PathSimplifier,page) {
		
		var orderload = layer.load(0, {
			shade:  [0.3,'#fff']
		});
		$('.carlist').css('display', 'none');
		$('.orderlist').css('display', 'block');
		$.ajax({
			type: "post",
			url: "{:url('orders')}",
			data: {
				id: id,
				page:page,
				pagesize:20,
			},
			success: function(res) {
				
				layer.close(orderload);
				if(res.code == 1) {
					if(typeof res == 'string') {
						origin.order = JSON.parse(res).data;
					} else {
						origin.order = res.data;
					}
					
					for(var orderidx = 0; orderidx < origin.order.length; orderidx++) {
						//加评星
						orderlistshow(orderidx, 5, origin.order);
						orderulheight()
						addOrderMarker(orderidx, origin, SimpleMarker);
					};
					//点击订单修改路线
					for(var j = 0; j < origin.order.length; j++) {
						origin.order[j].point.on('click', function() {
							map.remove(car);
							for(var item in this) {
								for(var item1 in this[item]) {
									if(item1 == 'cont') {
										orderid = this[item][item1].orderid
									};
								};
							};
							openmessage(map, this, SimpleInfoWindow, infoWindow, 2);
							ajaxpath(orderid, pathSimplifierIns, SimpleInfoWindow,infoWindow,PathSimplifier);
						});
					};
					$('.orderlist ul li').on('click', function() {
						var orderlistidx = $(this).index();
						orderid = origin.order[orderlistidx].order_id;
						map.remove(car);
						openmessage(map, origin.order[orderlistidx].point, SimpleInfoWindow, infoWindow, 2);
						ajaxpath(orderid, pathSimplifierIns, SimpleInfoWindow,infoWindow,PathSimplifier);
					})
				};
			},
					error:function(){
						layer.close(carload);
						Err('请求失败')
					}
		})
	}
	//请求数据path
	function ajaxpath(orderid, pathSimplifierIns, SimpleInfoWindow,infoWindow,PathSimplifier) {
		var pathload = layer.load(0, {
			shade:  [0.3,'#fff']
		});
		$.ajax({
			type: "post",
			data: {
				oid: orderid
			},
			url: "{:url('/admin/order/getTrack')}",
			success: function(res) {
				
				layer.close(pathload);
				var allpath = [];
				if(typeof res == 'string') {
					var opath1 = JSON.parse(res).data;
				} else {
					var opath1 = res.data;
				}
				var opath2 = [];
				var opath = [];
				
				if(opath1.length > 1) {
					for(var rankidx = 0; rankidx < opath1.length; rankidx++) {
						opath2.push(opath1[rankidx].time);
					}
					opath2.sort();
					for(var k = 0; k < opath2.length; k++) {
						for(var j = 0; j < opath1.length; j++) {
							if(opath2[k] == opath1[j].time) {
								opath.push(opath1[j]);
							}
						}
					}
					for(var oi = 0; oi < opath.length; oi++) {
						var oarr = [];
						oarr.push(opath[oi].longitude);
						oarr.push(opath[oi].latitude);
						allpath.push(oarr);
					}

					initPage(PathSimplifier, map, allpath, pathSimplifierIns);
				} else {
					Err('暂无轨迹信息');
				}
			},
					error:function(){
						layer.close(carload);
						Err('请求失败')
					}
		})
	}
	//添加车辆节点
	function addcarMarker(origin, caridx, SimpleMarker) {
		var carimg;
		if(origin.car[caridx].work_state==3) {
			pointimg='{$static_dir}/assets/img/car.png'
		}else if(origin.car[caridx].work_state==4){
			pointimg='{$static_dir}/assets/img/car.png'
		}else{
			pointimg='{$static_dir}/assets/img/car.png'
		};
		origin.car[caridx].point = new SimpleMarker({
			//普通文本
			iconStyle: {
				src: pointimg,
				style: {
					width: '15px',
					height: '30px'
				}
			},
			position: origin.car[caridx].loc,
			cont: {
				carid: origin.car[caridx].car_id,
				driverid: origin.car[caridx].driver_id,
				num: origin.car[caridx].number,
				loc: origin.car[caridx].loc,
				name: origin.car[caridx].name,
				phone: origin.car[caridx].phone,
				work_state: origin.car[caridx].work_state
			}
		});
		origin.car[caridx].point.setMap(map);
	}
	//添加订单节点
	function addOrderMarker(i, origin, SimpleMarker) {
		var iconStyles = SimpleMarker.getBuiltInIconStyles('fresh');
		origin.order[i].path=[];
		origin.order[i].path.push(origin.order[i].from_lon-0);
		origin.order[i].path.push(origin.order[i].from_lat-0);
		origin.order[i].point = new SimpleMarker({ 
			//普通文本
			iconStyle: iconStyles[2],
			//图标文字
			iconLabel: {
				//A,B,C.....
				innerHTML: i + 1,
				style: {
					color: '#fff'
				}
			}, 
			map: map,
			position: origin.order[i].path,
			path: origin.order[i].path,
			cont: {
				money:origin.order[i].order_money,
				time:origin.order[i].orders_time,
				drivername: origin.order[i].driver_name,
				begin: origin.order[i].departure,
				end: origin.order[i].destination,
				orderid: origin.order[i].order_id
			}
		});
		origin.order[i].point.setMap(map);
	};

});
//列表ul高度
function ulheight() {
	
	var carlistul = $('.carlist-list ul li').height()*5;
	for(var carlistli = 0; carlistli < $('.carlist-list ul li').length; carlistli++) {
		carlistul += ($('.carlist-list ul li').height()+20)
	};
	$('.carlist-list ul').height(carlistul);
	var myScroll = new IScroll('.carlist-list', {
		mouseWheel: true,
		disableMouse: true,
	});
	
}
function orderulheight() {
	
	var orderlistul = 0;
	for(var orderlistli = 0; orderlistli < $('.carlist-list ul li').length; orderlistli++) {
		orderlistul += $('.carlist-list ul li').height()
	};
	$('.carlist-list ul').height(orderlistul);
	var myScroll = new IScroll('.orderlist-list', {
		mouseWheel: true,
		disableMouse: true,
	});
}
//清除地图上得到所有节点
function clearall(origin, map) {
	for(var delcaridx = 0; delcaridx < origin.car.length; delcaridx++) {
		map.remove(origin.car[delcaridx].point);
	};
	for(var delorderidx = 0; delorderidx < origin.order.length; delorderidx++) {
		map.remove(origin.order[delorderidx].point);
	};
	$('.carlist').css('display', 'block');
	$('.orderlist').css('display', 'none');

}
//清除地图上除了点击的节点以外的所有节点
function clear(origin, obj, map) {
	
	for(var delidx = 0; delidx < origin.car.length; delidx++) {
		if(origin.car[delidx].point){
		if(origin.car[delidx].point === obj) {
			console.log('noclear')
		} else {
			console.log('clear')
			map.remove(origin.car[delidx].point);
		};
		}
	};
	
	$('.carlist').css('display', 'none');
	$('.orderlist').css('display', 'block');

}
//清除地图上所有订单节点
function clearorder(origin, map) {
	for(var delorderidx = 0; delorderidx < origin.order.length; delorderidx++) {
		map.remove(origin.order[delorderidx].point);
	};
	

}
//车辆列表
function carlistshow(caridx, obj) {
	var state='';
	if(obj.car[caridx].work_state==1){
		state='执行任务中'
	}else if(obj.car[caridx].work_state==2){
		state='有预约订单'
	}else if(obj.car[caridx].work_state==3){
		state='听单中'
	}else{
		state='下班'
	}
	$('.carlist ul').append(`
		<li style="height: 40px;padding: 10px 0;border-top: 1px solid #ccc;cursor: pointer;">
			<div class="am-u-sm-2" style="">
				<div style="border:1px solid #5FB878;margin:0;color:#5FB878;border-radius:50%;width:20px;height:20px;font-size:12px;line-height:20px;text-align:center">${caridx+1}</div>
			</div>
			<div class = "am-u-sm-10 ">
				<div class = "am-u-sm-6  am-text-truncate" style="font-size:12px">${obj.car[caridx].number}</div>
				<div class = "am-u-sm-6 cl-p  am-text-truncate" style="font-size:12px">
					${obj.car[caridx].name}&nbsp;${state}
					
				</div>
			</div>
			
		</li>`);

}
//订单列表
function ordertitle(number){
	$('.ordertitle').html(number)
}
function orderlistshow(i, star, obj) {
	var orderstate='';
	if(obj[i].order_state==1){
		orderstate='待审核';
	}else if(obj[i].order_state==3){
		orderstate='已拒绝';
	}else if(obj[i].order_state==4){
		orderstate='待用车';
	}else if(obj[i].order_state==5){
		orderstate='已派车';
	}else if(obj[i].order_state==6){
		orderstate='接驾中';
	}else if(obj[i].order_state==7){
		orderstate='已到达出发地';
	}else if(obj[i].order_state==8){
		orderstate='已到达目的地';
	}else if(obj[i].order_state==9){
		orderstate='待支付';
	}else if(obj[i].order_state==10){
		orderstate='待评价';
	}else if(obj[i].order_state==11){
		orderstate='已完成';
	}else if(obj[i].order_state==12){
		orderstate='已取消';
	}else if(obj[i].order_state==13){
		orderstate='已终止';
	}else if(obj[i].order_state==14){
		orderstate='已取消';
	}
	if(obj[i].complete_time){
		complete_time=obj[i].complete_time
	}else{
		complete_time='-'
	}
	var starimg;
	$('.orderlist ul').append(`
		<li style="height: 60px;padding: 10px 0;border-top: 1px solid #ccc;cursor: pointer;">
			<div class="am-u-sm-2" style="padding:5px;">
				<div style="border:1px solid #5FB878;margin:0;color:#5FB878;border-radius:50%;width:20px;height:20px;font-size:12px;line-height:20px;text-align:center">${i+1}</div>
			</div>
			<div class = "am-u-sm-6 cl-p">
				<div class = "am-u-sm-12 cl-p am-text-truncate" style="font-size:12px">${obj[i].orders_time}</div>
				<div class = "am-u-sm-12 cl-p am-text-truncate" style="font-size:12px">${complete_time}</div>
			</div>
			<div class="am-u-sm-3">
				<div class = "am-u-sm-12 cl-p am-text-truncate" style="font-size:12px;text-align:center">${orderstate}</div>
				<div class = "am-u-sm-12 cl-p am-text-truncate star" style="font-size:12px">
					
				</div>
			</div>
	</li>`);
	//判断星级
	for(var k = 0; k < parseInt(star); k++) {
		$('.star').append(`<img style="width:20%;height:12px" src="{$static_dir}/assets/img/star-on.png"/>`);
	};
	if(star - parseInt(star) > 0) {
		$('.star').append(`<img style="width:20%;height:12px" src="{$static_dir}/assets/img/star-half.png"/>`);
	};
	for(var l = 0; l < 5 - Math.ceil(star); l++) {
		$('.star').append(`<img style="width:20%;height:12px" src="{$static_dir}/assets/img/star-off.png"/>`);
	};

}
//点击图标获取订单信息
function getordercont(obj, ordercont, PathSimplifier, map, pathSimplifierIns) {
	//	pathSimplifierIns.show();
	for(var index in obj) {
		for(var index1 in obj[index]) {
			if(index1 == "cont") {
				idx = index;
				ordercont = obj[index].cont;
				ordercont.path = obj[index].path;
			};
		};
	};

	//	initPage(PathSimplifier, map, ordercont, pathSimplifierIns)
}
//规划路径
function getpath(obj, map, driving, SimpleMarker, SimpleInfoWindow) {
	var arr;
	var content;

	for(var index in obj) {
		for(var index1 in obj[index]) {
			if(index1 == "cont") {
				idx = index;
				arr = obj[index].path;
				content = obj[index].cont;
			};
		};
	};
	var iconStyles = SimpleMarker.getBuiltInIconStyles('fresh');

	//设置数据
	driving.search(new AMap.LngLat(arr[0][0], arr[0][1]), new AMap.LngLat(arr[arr.length - 1][0], arr[arr.length - 1][1]));
	map.setZoomAndCenter(13, arr[arr.length - 1]);
};

//轨迹
function initPage(PathSimplifier, map, path, pathSimplifierIns) {
	pathSimplifierIns.show()
	//订单轨迹速度
	var alljourney = 0;
	for(var pidx = 0; pidx < path.length - 1; pidx++) {
		var journey = Math.sqrt(Math.pow((path[pidx][0] - path[pidx + 1][0]), 2) + Math.pow((path[pidx][1] - path[pidx + 1][1]), 2)) * 111000;
		alljourney += journey;
	}

	pathSimplifierIns.clearPathNavigators();
	//创建组件实例
	//这里构建两条简单的轨迹，仅作示例
	pathSimplifierIns.setData([{
		name: '轨迹',
		path: path
	}]);

	//创建一个巡航器
	var navg0 = pathSimplifierIns.createPathNavigator(0, //关联第1条轨迹
		{
			loop: true, //循环播放
			speed: alljourney / 10,
			pathNavigatorStyle: {
				width: 16,
				height: 32,
				content: PathSimplifier.Render.Canvas.getImageContent('{$static_dir}/assets/img/car.png', onload, onerror),
				strokeStyle: null,
				fillStyle: null
			}
		});

	navg0.start();
}

//打开信息窗体
function openmessage(map, obj, SimpleInfoWindow, infoWindow, type) {
	var arr, idx, content, pos,state;
	for(var index in obj) {
		for(var index1 in obj[index]) {
			if(index1 == "cont") {
				idx = index;
				arr = obj[index].path;
				pos = obj[index].cont.loc;
				content = obj[index].cont;
			};
		};
	};
	
	
	if(type == 1) {
		if(content.work_state==1){
		state='执行任务中'
	}else if(content.work_state==2){
		state='有预约订单'
	}else if(content.work_state==3){
		state='听单中'
	}else{
		state='下班'
	}
		infoWindow = new SimpleInfoWindow({
			infoTitle: '<strong>' + content.name + '('+state+')</strong>',
			infoBody: `<div><div">电话：${content.phone}</div><div>车牌号:${content.num}</div></div>`,
			offset: new AMap.Pixel(0, -31)
		});
	} else {
		console.log(content)
		infoWindow = new SimpleInfoWindow({
			infoTitle: '<strong>' + content.drivername + '</strong>',
			infoBody: `<div><div>司机姓名:${content.drivername}</div><div>出发地:${content.begin}</div><div>目的地:${content.end}</div><div>订单花费:${content.money}</div></div>`,
			offset: new AMap.Pixel(0, -31)
		});
	}
	infoWindow.open(map, obj.getPosition());
}